<template>
  <div class="menu-add">
    <div class="page-header">
      <h2>添加菜单</h2>
      <p>创建新的系统菜单</p>
    </div>

    <div class="add-form-container">
      <el-form
        ref="menuFormRef"
        :model="menuForm"
        :rules="menuRules"
        label-width="120px"
        class="menu-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="name">
              <el-input
                v-model="menuForm.name"
                placeholder="请输入菜单名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单路径" prop="path">
              <el-input
                v-model="menuForm.path"
                placeholder="请输入菜单路径，如：/users"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="父级菜单" prop="parentId">
              <el-tree-select
                v-model="menuForm.parentId"
                :data="parentMenuOptions"
                :props="{ label: 'name', value: 'id' }"
                placeholder="请选择父级菜单"
                clearable
                check-strictly
                :render-after-expand="false"
                :loading="loadingMenus"
                loading-text="加载菜单中..."
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单图标" prop="icon">
              <el-select
                v-model="menuForm.icon"
                placeholder="请选择图标"
                clearable
                filterable
              >
                <el-option
                  v-for="icon in iconOptions"
                  :key="icon.value"
                  :label="icon.label"
                  :value="icon.value"
                >
                  <span style="display: flex; align-items: center;">
                    <el-icon style="margin-right: 8px;">
                      <component :is="ElementPlusIconsVue[icon.value]" />
                    </el-icon>
                    {{ icon.label }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number
                v-model="menuForm.sort"
                :min="0"
                :max="9999"
                placeholder="排序号"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="isActive">
              <el-radio-group v-model="menuForm.isActive">
                <el-radio :value="true">启用</el-radio>
                <el-radio :value="false">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            创建菜单
          </el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import { useMenuStore } from '@/stores/menu'
const router = useRouter()
const menuFormRef = ref()
const loading = ref(false)
const loadingMenus = ref(false) // 加载菜单数据的状态
const useMenustore=useMenuStore()
// 图标选项
const iconOptions = [
  { label: '仪表盘', value: 'Odometer' },
  { label: '用户', value: 'User' },
  { label: '锁定', value: 'Lock' },
  { label: '菜单', value: 'Menu' },
  { label: '设置', value: 'Setting' },
  { label: '文档', value: 'Document' },
  { label: '列表', value: 'List' },
  { label: '加号', value: 'Plus' },
  { label: '工具', value: 'Tools' },
  { label: '监控', value: 'Monitor' },
  { label: '首页', value: 'House' },
  { label: '用户填充', value: 'UserFilled' }
]

// 父级菜单选项 - 将从数据库动态获取
const parentMenuOptions = ref([
  {
    id: null,
    name: '顶级菜单',
    children: []
  }
])

// 表单数据
const menuForm = reactive({
  name: '',
  path: '',
  icon: '',
  parentId: null,
  sort: null,
  isActive: true,
})

// 验证规则
const menuRules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { min: 2, max: 20, message: '菜单名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入菜单路径', trigger: 'blur' },
    { pattern: /^\/[a-zA-Z0-9/_-]*$/, message: '路径格式不正确，应以/开头', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ]
}

// 方法
const loadParentMenus = async () => {
  loadingMenus.value = true
  try {
    console.log('开始加载父级菜单列表...')
    
    // 调用菜单存储的API方法获取菜单树
    const menuTree = await useMenustore.getmenutree()
    console.log('获取到的菜单树:', menuTree)
    
    // 转换菜单数据格式，添加顶级菜单选项
    const formattedMenus = [
      {
        id: null,
        name: '顶级菜单',
        children: []
      }
    ]
    
    // 递归函数，将菜单树转换为下拉选择器所需的格式
    const formatMenuForSelect = (menu) => ({
      id: menu.id,
      name: menu.name,
      children: menu.children ? menu.children.map(formatMenuForSelect) : []
    })
    
    // 添加从API获取的菜单
    if (menuTree && Array.isArray(menuTree)) {
      formattedMenus.push(...menuTree.map(formatMenuForSelect))
    }
    
    parentMenuOptions.value = formattedMenus
    console.log('父级菜单列表加载完成:', parentMenuOptions.value)
    
  } catch (error) {
    console.error('加载父级菜单列表失败:', error)
    ElMessage.error('加载父级菜单列表失败: ' + (error.message || '未知错误'))
  } finally {
    loadingMenus.value = false
  }
}
//添加菜单行
const handleSubmit = async () => {
  try {
    // 表单验证
    await menuFormRef.value.validate()
    
    loading.value = true
    
    // 模拟API调用
    console.log(menuForm);
    
    const response =await useMenustore.addMenu(menuForm)
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 实际情况下这里应该是创建菜单的API请求
    console.log('创建菜单:', menuForm)
    console.log(response);
    
    ElMessage.success('菜单创建成功')
    
    // 跳转到菜单列表
    router.push('/menus/list')
    
  } catch (error) {
    console.error('创建菜单失败:', error)
    if (error) {
      ElMessage.error('创建菜单失败: ' + (error.message || '请检查表单输入'))
    }
  } finally {
    loading.value = false
  }
}

const handleReset = () => {
  menuFormRef.value.resetFields()
}

const handleCancel = () => {
  router.push('/menus/list')
}

// 生命周期
onMounted(() => {
  loadParentMenus()
})
</script>

<style scoped>
.menu-add {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 5px 0;
  color: #333;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.add-form-container {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.menu-form {
  max-width: 800px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-tree-select) {
  width: 100%;
}
</style>
